<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="反射," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="反射的概念与功能Java反射机制是在运行状态中，对与任意一个类，都能知道这个类的所以属性和方法；对于任意一个对象，都能够调用它的任意一个方法，这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。Java反射机制主要提供了以下的功能：

在运行时判断任意一个对象所属的类
在运行时构造任意一个类的对象
在运行时判断任意一个类所具有的成员变量和方法
在运行时调用任意一个对象的方法">
<meta property="og:type" content="article">
<meta property="og:title" content="Java基础--反射">
<meta property="og:url" content="https://zitongchen.github.io/2017/08/16/Java基础--反射/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="反射的概念与功能Java反射机制是在运行状态中，对与任意一个类，都能知道这个类的所以属性和方法；对于任意一个对象，都能够调用它的任意一个方法，这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。Java反射机制主要提供了以下的功能：

在运行时判断任意一个对象所属的类
在运行时构造任意一个类的对象
在运行时判断任意一个类所具有的成员变量和方法
在运行时调用任意一个对象的方法">
<meta property="og:updated_time" content="2017-09-16T10:24:58.739Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java基础--反射">
<meta name="twitter:description" content="反射的概念与功能Java反射机制是在运行状态中，对与任意一个类，都能知道这个类的所以属性和方法；对于任意一个对象，都能够调用它的任意一个方法，这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。Java反射机制主要提供了以下的功能：

在运行时判断任意一个对象所属的类
在运行时构造任意一个类的对象
在运行时判断任意一个类所具有的成员变量和方法
在运行时调用任意一个对象的方法">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/08/16/Java基础--反射/"/>





  <title> Java基础--反射 | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/08/16/Java基础--反射/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java基础--反射
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-16T00:00:00+08:00">
                2017-08-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/08/16/Java基础--反射/" class="leancloud_visitors" data-flag-title="Java基础--反射">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="反射的概念与功能"><a href="#反射的概念与功能" class="headerlink" title="反射的概念与功能"></a>反射的概念与功能</h1><p>Java反射机制是在运行状态中，对与任意一个类，都能知道这个类的所以属性和方法；对于任意一个对象，都能够调用它的任意一个方法，这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。<br>Java反射机制主要提供了以下的功能：</p>
<ul>
<li>在运行时判断任意一个对象所属的类</li>
<li>在运行时构造任意一个类的对象</li>
<li>在运行时判断任意一个类所具有的成员变量和方法</li>
<li>在运行时调用任意一个对象的方法</li>
</ul>
<h1 id="Class类"><a href="#Class类" class="headerlink" title="Class类"></a>Class类</h1><p>在面向对象的世界里，万事万物皆对象，类也是对象，类是java.lang.Class类的实例对象，但Java语言中静态的成员，普通数据类型不是对象</p>
<p>Class.forName(“类的全称”):</p>
<ul>
<li>不仅表示了类的类类型，还代表了动态加载类</li>
<li>编译时刻加载类是静态加载类，运行时刻加载类是动态加载类</li>
</ul>
<p>new 创建对象是静态加载类，在编译时刻就需要加载所以的可能使用到的类</p>
<h2 id="创建类的实例化对象有有三种方式："><a href="#创建类的实例化对象有有三种方式：" class="headerlink" title="创建类的实例化对象有有三种方式："></a>创建类的实例化对象有有三种方式：</h2><ul>
<li><p>利用Object类的getClass()方法，但需要有类的实例对象才能用</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">Foo foo = new Foo();</div><div class="line">Class fooClass = foo.getClass();</div></pre></td></tr></table></figure>
</li>
<li><p>利用“类.class”形式获取得Class类的对象</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">Class fooClass = foo.class;</div></pre></td></tr></table></figure>
</li>
<li><p>利用Class类提供的forName(“类全称”),JDBCv中有使用</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">Class Foo = Class.forName(&quot;java.util.Date&quot;);</div></pre></td></tr></table></figure>
</li>
</ul>
<p>根据类类型生成类的实例：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">//方式一：需要该类有无参的构造函数</span></div><div class="line">Foo foo1 = (Foo) c3.newInstance();</div><div class="line"><span class="comment">//方式二：根据构造函数的参数类型，生成类的实例</span></div><div class="line">Foo foo2 = (Foo) c3.getConstructor(String.class).newInstance(<span class="string">"Tony"</span>);</div></pre></td></tr></table></figure></p>
<p>根据类类型获取类的基本信息：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassDemo2</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		Class c1 = <span class="keyword">int</span>.class;<span class="comment">//int的类类型</span></div><div class="line">		Class c2 = String.class;<span class="comment">//String类的类类型</span></div><div class="line">		Class c3 = <span class="keyword">double</span>.class;</div><div class="line">		Class c4 = Double.class;</div><div class="line">		Class c5 = <span class="keyword">void</span>.class;</div><div class="line">		System.out.println(c1.getSimpleName());</div><div class="line">		System.out.println(c2.getName());</div><div class="line">		System.out.println(c2.getSimpleName());<span class="comment">//若是引用类型的对象，则显示类名</span></div><div class="line">		System.out.println(c3.getName());</div><div class="line">		System.out.println(c4.getName());</div><div class="line">		System.out.println(c5.getName());</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">/**运行结果：int, java.lang.String, String, double, java.lang.Double, void</span></div><div class="line">*/</div></pre></td></tr></table></figure></p>
<h2 id="获取成员变量的信息"><a href="#获取成员变量的信息" class="headerlink" title="获取成员变量的信息"></a>获取成员变量的信息</h2><p>成员变量也是对象，java.lang.reflect.Filed类封装了关于成员变量的操作</p>
<ul>
<li>getFields()方法获取的是所以public的成员变量的信息</li>
<li>getDeclaredFields()方法获取的是类中所用的成员变量的信息</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassReflectFields</span></span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		<span class="comment">//打印String对象的成员变量</span></div><div class="line">		printFiledMessage(<span class="string">"Tony"</span>);</div><div class="line">	&#125;</div><div class="line"><span class="comment">/**</span></div><div class="line">	 * 获取成员变量的信息</div><div class="line">	 */</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printFiledMessage</span><span class="params">(Object obj)</span> </span>&#123;</div><div class="line">		Class c = obj.getClass();<span class="comment">//获取String的类类型</span></div><div class="line">		Field[] fs = c.getFields();<span class="comment">//获取String类类型中public的成员变量</span></div><div class="line">		<span class="keyword">for</span>(Field field : fs) &#123;</div><div class="line">			Class fieldType = field.getType(); <span class="comment">//获取成员变量的类类型</span></div><div class="line">			String typeName = fieldType.getSimpleName();</div><div class="line">			String fileName = field.getName();<span class="comment">//获取成员变量名</span></div><div class="line">			System.out.println(typeName + <span class="string">" "</span> + fileName);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="获取构造函数的信息"><a href="#获取构造函数的信息" class="headerlink" title="获取构造函数的信息"></a>获取构造函数的信息</h2><p> 构造函数也是对象，java.lang.Constructor中封装了构造函数的信息</p>
<ul>
<li>getConstructors获取所以的public的构造函数</li>
<li>getDeclaredConstructors得到对象所以的构造函数</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassReflectConstructors</span></span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		<span class="comment">//打印对象的构造函数</span></div><div class="line">		ClassUtil.printConMessage(<span class="string">"Tony"</span>);</div><div class="line">	&#125;</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printConMessage</span><span class="params">(Object obj)</span> </span>&#123;</div><div class="line">		Class c = obj.getClass();</div><div class="line">		Constructor[] cs = c.getDeclaredConstructors();</div><div class="line">		<span class="keyword">for</span> (Constructor constructor : cs) &#123;</div><div class="line">			System.out.print(constructor.getName() + <span class="string">"("</span>);</div><div class="line">			Class[] paramType = constructor.getParameterTypes();</div><div class="line">			<span class="keyword">for</span> (Class class1 : paramType) &#123;</div><div class="line">				System.out.print(class1.getSimpleName() + <span class="string">", "</span>);	</div><div class="line">			&#125;</div><div class="line">			System.out.println(<span class="string">")"</span>);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">｝</div></pre></td></tr></table></figure>
<h2 id="获取类类型的方法"><a href="#获取类类型的方法" class="headerlink" title="获取类类型的方法"></a>获取类类型的方法</h2><p>Method类，方法的对象，一个成员方法就是一个Method对象</p>
<ul>
<li>getMethods()获取的是所以public的函数</li>
<li>getDeclaredMethods()获取类类型的所以方法</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ClassReflectMethod</span></span>&#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</div><div class="line">        <span class="comment">//打印类类型的方法</span></div><div class="line">        printClassMethodMessage(<span class="string">"Tony"</span>);</div><div class="line">    &#125;</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printClassMethodMessage</span><span class="params">(Object obj)</span> </span>&#123;</div><div class="line">		<span class="comment">//要获取类的信息，首先要获取类的类类型</span></div><div class="line">		Class c = obj.getClass();</div><div class="line">		<span class="comment">//获取类的名称</span></div><div class="line">		System.out.println(<span class="string">"类的名称："</span> + c.getName());</div><div class="line">		Method[] ms = c.getDeclaredMethods();</div><div class="line">		<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i&lt; ms.length; i++) &#123;</div><div class="line">			<span class="comment">//得到方法的返回值的类类型</span></div><div class="line">			Class returnType = ms[i].getReturnType();</div><div class="line">			System.out.print(returnType.getSimpleName() + <span class="string">" "</span>);</div><div class="line">			<span class="comment">//获取方法名称</span></div><div class="line">			System.out.print(ms[i].getName() + <span class="string">"("</span>);</div><div class="line">			<span class="comment">//获取方法的参数</span></div><div class="line">			Class[] paramTypes = ms[i].getParameterTypes();</div><div class="line">			<span class="keyword">for</span> (Class class1 : paramTypes) &#123;</div><div class="line">				System.out.print(class1.getName() + <span class="string">","</span>);</div><div class="line">			&#125;</div><div class="line">			System.out.println(<span class="string">")"</span>);</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="方法的反射"><a href="#方法的反射" class="headerlink" title="方法的反射"></a>方法的反射</h1><p>通过反射获取指定的方法：</p>
<ul>
<li>获取类的类类型</li>
<li>获取类类型的Method对象，由名称和参数列表来决定</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodDemo</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		Class a = A.class;</div><div class="line">		A obj;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			obj = (A) a.newInstance();</div><div class="line">			<span class="comment">//获取类的无参方法print方法</span></div><div class="line">			Method  m1 = a.getMethod(<span class="string">"print"</span>);</div><div class="line">			m1.invoke(obj);</div><div class="line">			System.out.println(<span class="string">"==========="</span>);</div><div class="line">            <span class="comment">//第一个参数为方法的名称，第二个是可变参数，是对应方法的参数类类型，下面两个获取Method的效果一致</span></div><div class="line">			<span class="comment">//Method m = a.getMethod("print", new Class[]&#123;int.class, int.class&#125;);</span></div><div class="line">			Method m2 = a.getMethod(<span class="string">"print"</span>, <span class="keyword">int</span>.class, <span class="keyword">int</span>.class);</div><div class="line">			m2.invoke(obj, <span class="number">1</span>, <span class="number">4</span>);</div><div class="line">			System.out.println(<span class="string">"==========="</span>);</div><div class="line">			<span class="comment">/*</span></div><div class="line">			 * 方法的反射操作</div><div class="line">			 * 方法的反射操作是通过mX对象来进行方法的调用的和obj.print("a", "b")调用的效果一样</div><div class="line">			 * 方法如果没有返回值返回null,有返回值返回具体的返回值</div><div class="line">			 * Object o = m3.invoke(obj, new Object[]&#123;"String", "String"&#125;);</div><div class="line">			 */</div><div class="line">			Method m3 = a.getMethod(<span class="string">"print"</span>, String.class, String.class);</div><div class="line">			m3.invoke(obj, <span class="string">"chen"</span>, <span class="string">"zitoing"</span>);</div><div class="line">		&#125; <span class="keyword">catch</span> (InstantiationException e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125; <span class="keyword">catch</span> (IllegalAccessException e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125; <span class="keyword">catch</span> (NoSuchMethodException nsme) &#123;</div><div class="line">			nsme.printStackTrace();</div><div class="line">		&#125; <span class="keyword">catch</span> (InvocationTargetException ite) &#123;</div><div class="line">			ite.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">			</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">print</span><span class="params">()</span></span>&#123;</div><div class="line">		System.out.println(<span class="string">"通过反射调用方法！"</span>);</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">print</span><span class="params">(<span class="keyword">int</span> a, <span class="keyword">int</span> b)</span></span>&#123;</div><div class="line">		System.out.println(a + b);</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">print</span><span class="params">(String a, String b)</span></span>&#123;</div><div class="line">		System.out.println(a + <span class="string">", "</span> + b);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="集合中的泛型"><a href="#集合中的泛型" class="headerlink" title="集合中的泛型"></a>集合中的泛型</h1><p>反射的操作都是编译之后的操作，Java中集合泛型在编译后是去泛型的，集合中使用泛型是防止错误的输入，只在编译阶段有效；可以通过方法的反射操作，绕过编译<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MethodDemo3</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		ArrayList list = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">		ArrayList&lt;String&gt; list1 = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">		list1.add(<span class="string">"hello"</span>);</div><div class="line">		<span class="comment">//list1.add(1);若添加的不是String类型的数据会出错</span></div><div class="line">		Class c1 = list.getClass();</div><div class="line">		Class c2 = list1.getClass();</div><div class="line">		System.out.println(c1 == c2);</div><div class="line">		<span class="comment">//反射的操作都是编译之后的操作</span></div><div class="line">		<span class="comment">/*</span></div><div class="line">		 * c1 == c2 结果返回true说明编译之后集合的泛化是去泛型化的</div><div class="line">		 * Java中的集合泛型，是防止错误的输入，只在编译阶段有效</div><div class="line">		 * 绕过编译就无效了</div><div class="line">		 * 验证：我们可以通过方法的反射操作，绕过编译</div><div class="line">		 * </div><div class="line">		 */</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">                <span class="comment">//执行下面的方法输出的结果是：2，[hello, 20]</span></div><div class="line">			Method m  = c2.getMethod(<span class="string">"add"</span>, Object.class);</div><div class="line">			m.invoke(list1, <span class="number">20</span>);</div><div class="line">			System.out.println(list1.size());</div><div class="line">			System.out.println(list1);</div><div class="line">			<span class="comment">//执行下面的循环会抛出类型转换异常 java.lang.ClassCastException，因为在list1中包含了int类型的数据</span></div><div class="line">			<span class="comment">/*for (String string : list1) &#123;</span></div><div class="line">				System.out.println(string);</div><div class="line">			&#125;*/</div><div class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/反射/" rel="tag"># 反射</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/15/SpringMVC基础学习之文件的上传与下载/" rel="next" title="SpringMVC基础学习之文件的上传与下载">
                <i class="fa fa-chevron-left"></i> SpringMVC基础学习之文件的上传与下载
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/18/Java基础--Socket/" rel="prev" title="Java基础--Socket">
                Java基础--Socket <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#反射的概念与功能"><span class="nav-number">1.</span> <span class="nav-text">反射的概念与功能</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Class类"><span class="nav-number">2.</span> <span class="nav-text">Class类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建类的实例化对象有有三种方式："><span class="nav-number">2.1.</span> <span class="nav-text">创建类的实例化对象有有三种方式：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取成员变量的信息"><span class="nav-number">2.2.</span> <span class="nav-text">获取成员变量的信息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取构造函数的信息"><span class="nav-number">2.3.</span> <span class="nav-text">获取构造函数的信息</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#获取类类型的方法"><span class="nav-number">2.4.</span> <span class="nav-text">获取类类型的方法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#方法的反射"><span class="nav-number">3.</span> <span class="nav-text">方法的反射</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#集合中的泛型"><span class="nav-number">4.</span> <span class="nav-text">集合中的泛型</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
